import { transform } from "typescript";

export function base64decode(base64) {
  const binaryString = atob(base64);
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes.buffer;
}


export function transformPoints(msg) {

  let rbounds = msg._ranges_uint16.bounds;
  let rdata = base64decode(msg._ranges_uint16.points);
  let rview = new DataView(rdata);
  let num_ranges = rdata.byteLength / 2; // uint16

  let points1 = new Float32Array(num_ranges * 2);

  const points = [];
  // angle increment between points
  let angle_incr = (msg.angle_max - msg.angle_min) / num_ranges;

  let rrange = rbounds[1] - rbounds[0];
  let rmin = rbounds[0];

  for(let i=0; i<num_ranges; i+=2) {
    let offset = i * 2;
    let angle = msg.angle_min + i * angle_incr;

    let r_uint16 = rview.getUint16(offset, true);

    if(r_uint16 === 65535) {
      // points[2*i] = NaN;
      // points[2*i+1] = NaN;
      continue; // nan, -inf, inf mapped to 65535
    }

    let r = r_uint16 / 65534 * rrange + rmin; // valid values mapped to 0-65534
    

    points.push([r * Math.cos(angle), r * Math.sin(angle)])
    // points[2*i] = r * Math.cos(angle);
    // points[2*i+1] = r * Math.sin(angle);
  }

  return [points1, points];
}


export function transformPoints1(msg) {

  let bounds = msg._data_uint16.bounds;
  let points_data = base64decode(msg._data_uint16.points);
  let points_view = new DataView(points_data);

  let points = new Float32Array(Math.round(points_data.byteLength / 2));
  let points1 = []
  let xrange = bounds[1] - bounds[0];
  let xmin = bounds[0];
  let yrange = bounds[3] - bounds[2];
  let ymin = bounds[2];
  let zrange = bounds[5] - bounds[4];
  let zmin = bounds[4];

  for (let i = 0; i < points_data.byteLength / 6; i++) {
    let offset = i * 6;
    const x = (points_view.getUint16(offset, true) / 65535) * xrange + xmin;
    const y = (points_view.getUint16(offset + 2, true) / 65535) * yrange + ymin;
    const z = (points_view.getUint16(offset + 4, true) / 65535) * zrange + zmin;
    points[3 * i] = x;
    points[3 * i + 1] = y;
    points[3 * i + 2] = z;
  

    if(0 <= z && z <= 1) {
      points1.push([x,y,z])
    }
  }

  return [points ,points1];
}